import React from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import {
  Form, Input, DatePicker, Button, Card, Radio, Select, Switch,
} from 'antd';
import FormBody from 'xrc-form';
import moment from 'moment';
import WarpItem from '../../components/StandardFormRow/SimpleItem';
import Uploader from '../../components/Uploader';
import RichFields from '../../components/Activity/Form/RichFields';
import EditableTags from '../../components/EditableTags';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { interact } from '../../config/api';
import { statusOk } from '../../utils/httpcode';
// import styles from './style.less';

const handleUpload = (file) => {
  return new Promise((res, rej) => {
    interact('uploadImage')({ UpImg: file }).then(({ code, message }) => {
      if (code !== statusOk) {
        rej(message);
      }

      res(message.Url);
    });
  });
};

const { RangePicker } = DatePicker;

const ActivityBody = Form.create()((props) => {
  // 表单提交事件
  const handleSubmit = (e) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (err) {
        console.log(err);
        return false;
      }

      const params = {
        ...values,
        StartDate: values.ActDate[0] ? values.ActDate[0].format() : undefined,
        EndDate: values.ActDate[1] ? values.ActDate[1].format() : undefined,
        StartBookDate: values.BookDate[0] ? values.BookDate[0].format() : undefined,
        EndBookDate: values.BookDate[1] ? values.BookDate[1].format() : undefined,
      };

      const action = params.ActivityId ? 'activities/updateActivity' : 'activities/saveActivity';

      props.dispatch({
        type: action,
        payload: {
          params,
          success: (data) => {
            const result = {
              type: 'success',
              title: '保存活动成功',
              actions: (
                <div>
                  <Link to="/activity"><Button type="primary">查看列表</Button></Link>
                  <Link to={`/activity/edit/${data.ActivityId}`}><Button>返回活动</Button></Link>
                </div>
              ),
            };

            props.dispatch({ type: 'result/updateResult', payload: result });
            props.dispatch(routerRedux.push('/result'));
          },
        },
      });
    });
  };

  const data = props.detail || {};

  const attrs = [
    {
      name: 'ActivityId',
      options: {
        initialValue: data.ActivityId,
      },
    },
    {
      label: '所属分类',
      name: 'TypeId',
      element: (
        <Select style={{ width: '100%' }}>
          {
            (props.types || []).map(({ TypeId, TypeName }) => {
              return (
                <Select.Option key={`${TypeId}`}>{TypeName}</Select.Option>
              );
            })
          }
        </Select>
      ),
      options: {
        initialValue: `${data.TypeId || ((props.types || [])[0] || {}).TypeId}`,
        rules: [{
          required: true,
          message: '请选择所属分类',
        }],
      },
    },
    {
      label: '活动标题',
      name: 'Title',
      element: <Input placeholder="填写活动标题" />,
      options: {
        initialValue: data.Title,
        rules: [{
          required: true,
          message: '请填写活动标题',
        }],
      },
    },
    {
      label: '标签',
      name: 'Tags',
      element: <EditableTags />,
      options: {
        initialValue: data.Tags,
      },
    },
    {
      label: '概 述',
      name: 'Summary',
      element: <Input.TextArea placeholder="尽量少的词汇概述本次活动" />,
      options: {
        initialValue: data.Summary,
        rules: [{
          required: true,
          message: '请填写活动概述',
        }],
      },
    },
    {
      label: '活动地点',
      name: 'Location',
      element: <Input placeholder="填写活动地点, 比如上海-浦东" />,
      options: {
        initialValue: data.Location,
        rules: [{
          required: true,
          message: '请填写活动地点',
        }],
      },
    },
    {
      label: '活动时间',
      name: 'ActDate',
      element: <RangePicker style={{ width: '100%' }} placeholder={['开始日期', '结束日期']} />,
      options: {
        initialValue: [moment(data.StartDate), moment(data.EndDate)],
        rules: [{
          required: true,
          message: '请设置活动时间',
        }],
      },
    },
    {
      label: '预约时间',
      name: 'BookDate',
      element: <RangePicker style={{ width: '100%' }} placeholder={['开始日期', '结束日期']} />,
      options: {
        initialValue: [moment(data.StartBookDate), moment(data.EndBookDate)],
      },
    },
    {
      label: '封 面',
      name: 'Cover',
      element: <Uploader onUpload={handleUpload} />,
      options: {
        initialValue: data.Cover || '',
      },
    },
    {
      label: '费用简述',
      name: 'FeeBrief',
      element: <Input placeholder="一句话描述收费情况" />,
      options: {
        initialValue: data.FeeBrief,
      },
    },
    {
      label: '费用简述',
      element: (<RichFields data={data} form={props.form} />),
    },
    {
      label: '活动状态',
      name: 'Status',
      element: (
        <Radio.Group>
          <Radio value="0">草稿(不发布)</Radio>
          <Radio value="1">发布</Radio>
        </Radio.Group>
      ),
      options: {
        initialValue: `${data.Status}`,
      },
    },
    {
      label: '首页显示',
      name: 'ToIndex',
      element: (<Switch />),
      options: {
        valuePropName: 'checked',
        initialValue: data.ToIndex,
      },
    },
    {
      label: '首页滚动显示',
      name: 'ToSlider',
      element: (<Switch />),
      options: {
        valuePropName: 'checked',
        initialValue: data.ToSlider,
      },
    },
    {
      element: (
        <div style={{ marginTop: 32 }}>
          <Button type="primary" htmlType="submit">提交</Button>
          <Button style={{ marginLeft: 8 }}>取消</Button>
        </div>
      ),
    },
  ];

  const activity = {
    items: attrs,
    wrapItem: WarpItem,
    form: props.form,
  };

  return (
    <PageHeaderLayout title="活动维护">
      <Card bordered={false}>
        <Form onSubmit={handleSubmit} style={{ marginTop: 8 }}>
          <FormBody {...activity} />
        </Form>
      </Card>
    </PageHeaderLayout>
  );
});

export default connect(s => s.activities)(ActivityBody);
